<?php
declare(strict_types=1);

namespace App\Controller\Admin;

use App\Annotation\ModuleAndAction;
use App\Exception\BusinessException;
use App\Middleware\AdminMiddleware;
use App\Model\ContentItem;
use App\Model\ContentMenu;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\Utils\Str;
use Psr\Http\Message\ResponseInterface;
use stdClass;

/**
 * @AutoController()
 * @ModuleAndAction(module="管理后台:内容管理:栏目管理", icon="fa fa-sitemap")
 * @Middleware(AdminMiddleware::class)
 */
class MenuController extends BaseController
{
    public $model = ContentMenu::class;

    /**
     * @ModuleAndAction(module="管理后台:内容管理:栏目管理", action="查看列表")
     */
    public function getAllAsSelect(): ResponseInterface
    {
        return $this->response->json(static::genSuccessData(ContentMenu::getAllSelectOptions()));
    }

    protected function fixPostData(?array $data): ?array
    {
        if (!$data) {
            return null;
        }
        $dataNew = [];
        $fields = ['parent_id' => 'int', 'name' => 'str', 'name_id' => 'str', 'sort_number' => 'int'];
        foreach ($fields as $field => $fun) {
            if (!key_exists($field, $data)) {
                continue;
            }
            $value = ($fun . 'val')($data[$field]);
            if ((is_int($value) && $value > 0) || (is_string($value) && !empty($value))) {
                $dataNew[$field] = $value;
            }
        }
        if (!$dataNew) {
            return null;
        }
        $id = intval($data['id'] ?? 0);
        if ($id > 0) {
            $dataNew['id'] = $id;
        } else {
            if (empty($dataNew['name_id'] ?? '')) {
                $dataNew['name_id'] = Str::random();
            }
            if (empty($dataNew['name'] ?? '')) {
                $dataNew['name'] = '未命名栏目';
            }
        }
        $parentId = ($dataNew['parent_id'] ?? 0);
        if ($id > 0 && $parentId > 0 && !ContentMenu::canBeParentId($parentId, $id)) {
            throw new BusinessException(0, '父级ID错误，请确认！');
        }
        return $dataNew;
    }

    protected function fixListData(?array $data): ?array
    {
        $get = $this->request->query();
        $parentId = intval($get['parent_id'] ?? 0);
        $item = new stdClass();
        $item->id = 0;
        $item->parent_id = $parentId;
        $item->parents = ContentMenu::getFullParent($parentId);
        $item->name = '单击编辑新栏目';
        $item->name_id = '单击编辑唯一标识';
        $item->sort_number = 0;
        array_unshift($data, $item);
        return $data;
    }

    protected function afterDeleted($rowsCount, $idsArr, $soft): array
    {
        unset($soft);
        if (!$rowsCount) {
            throw new BusinessException(0, '没有数据被删除！');
        }
        $id = intval($idsArr[0] ?? 0);
        if ($id <= 0) {
            throw new BusinessException(0, 'ID未得到！');
        }
        $post = $this->request->post();
        $parentId = intval($post['parent_id'] ?? 0);
        if ($parentId < 0) {
            throw new BusinessException(0, 'parentId未得到！');
        }
        ContentMenu::query(true)->where('parent_id', '=', $id)->update(['parent_id' => $parentId]);
        ContentItem::query(true)->where('menu_id', '=', $id)->update(['menu_id' => $parentId]);
        return ['rows_count' => $rowsCount];
    }
}
